<template>
  <div class="my-table-content">
    <div class="search-bar">
      <div class="search-bar-inner">
        <el-form ref="searchFormRef" :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="科室" prop="deptId">
            <DeptSelector v-model="queryParams.deptId" :check-strictly="true" :clearable="true" />

            <!-- <el-cascader :options="[]" clearable placeholder="请选择科室" /> -->
          </el-form-item>

          <el-form-item label="类目" prop="type">
            <el-select
              v-model="queryParams.type"
              placeholder="请选择类目"
              clearable
              style="width: 130px"
            >
              <el-option
                v-for="(option, index) in routerTypeList"
                :key="index"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="classification">
            <el-select
              v-model="queryParams.classification"
              placeholder="请选择分类"
              clearable
              style="width: 130px"
            >
              <el-option
                v-for="(option, index) in cateList"
                :key="index"
                :label="option.name"
                :value="option.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select
              v-model="queryParams.state"
              placeholder="请选择状态"
              clearable
              style="width: 130px"
            >
              <el-option
                v-for="(option, index) in recordStates"
                :key="index"
                :label="option.text"
                :value="option.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间" prop="submitTime">
            <el-date-picker
              v-model="queryParams.submitTime"
              style="width: 240px"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item class="form-btn-group">
            <el-button plain @click="queryData">查询</el-button>
            <el-button type="primary" @click="handleUpdate({})">审核流配置</el-button>
            <!--
            <el-button type="primary" @click="handleAdd">新增</el-button>

            <el-button type="danger" @click="batchDelete">批量删除</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="common-panel">
      <div class="panel-body">
        <div class="my-table-wrapper">
          <el-table
            ref="multipleTable"
            class="custom-table cell-no-padding"
            border
            :stripe="false"
            style="width: 100%"
            tooltip-effect="dark"
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column  type="selection" width="50" /> -->
            <el-table-column type="index" width="60">
              <template #header> 序号 </template>
            </el-table-column>
            <el-table-column label="科室" :show-overflow-tooltip="true" prop="deptName" />

            <el-table-column label="类目" :show-overflow-tooltip="true" prop="type" width="120">
              <template #default="scope">
                {{ formatType(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column
              label="分类"
              :show-overflow-tooltip="true"
              prop="classification"
              width="120"
            >
              <template #default="scope">
                {{ formatClassification(scope.row.classification) }}
              </template>
            </el-table-column>
            <el-table-column label="标题" :show-overflow-tooltip="true" prop="title" />
            <el-table-column label="提交时间" :show-overflow-tooltip="true" prop="submitTime" />
            <el-table-column
              label="状态"
              :show-overflow-tooltip="true"
              prop="recordState"
              width="100"
            >
              <template #default="scope">
                {{ formatState(scope.row.recordState) }}
              </template>
            </el-table-column>
            <el-table-column
              label="创建人"
              :show-overflow-tooltip="true"
              prop="createName"
              width="120"
            />

            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  class="table-button"
                  @click="handleViewItem(scope.row)"
                  >审核</el-button
                >
                <!-- <el-button type="primary" link @click="handleViewItem(scope.row)">查看</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="panel-footer">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="queryData"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <tableDialog
      :options="dialogOptions"
      @confirm="handleConfirm"
      @close="handleClose"
    ></tableDialog>
    <!--
    <customDialog
      :options="dialogOptions"
      @confirm="handleConfirm"
      @close="handleClose"
    ></customDialog> -->
  </div>
</template>

<script setup>
  import { onMounted, reactive, ref, computed, defineAsyncComponent } from 'vue';
  import { useGoToPage } from '@/hooks/useGoToPage/index';
  import { useStore } from 'vuex';
  // import tableDialog from './components/tableDialog.vue';
  // import customDialog from './components/customDialog.vue';
  import { useHandleData } from '@/hooks/useHandleData/index';
  import { deleteSurveyTemplate as deleteData } from '@/api/satisfactionTemplate';
  import { postApprovalPage as queryList } from '@/api/handbookApproval/index';
  import DeptSelector from '@/components/common/businessComponent/DeptSelector.vue';
  import { useSubMenu } from '@/hooks/useSubMenu/index';
  import dayjs from 'dayjs';
  import { listMenu } from '@/api/system/menu';
  // const DeptSelector = defineAsyncComponent(() =>
  //   import('@/components/common/businessComponent/DeptSelector.vue'),
  // );
  const tableDialog = defineAsyncComponent(() => import('./components/tableDialog.vue'));
  const store = useStore();
  const addRoutes = computed(() => store.state.permission.addRoutes);

  const allEnums = store.state.app.allEnums;

  // 获取当前日期
  const today = dayjs();

  // 往前推30天
  const daysBefore = today.subtract(30, 'day');
  const queryFormState = {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    classification: undefined,
    type: undefined,
    submitTime: [daysBefore.format('YYYY-MM-DD'), today.format('YYYY-MM-DD')],
    state: undefined,
  };
  // 查询表单form
  const queryParams = reactive({ ...queryFormState });

  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 改变每页显示数量
  function handleSizeChange(val) {
    queryParams.pageSize = val;
    queryData();
  }
  // 重置查询条件
  function resetQuery() {
    let pageSize = queryParams.pageSize;
    Object.assign(queryParams, queryFormState);
    queryParams.pageSize = pageSize;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let params = {
        ...queryParams,
        submitTime: queryParams.submitTime
          ? {
              startValue: queryParams.submitTime[0] + ' 00:00:00',
              endValue: queryParams.submitTime[1] + ' 23:59:59',
            }
          : undefined,
        classification: queryParams.classification || undefined,
        deptId: queryParams.deptId ? queryParams.deptId[queryParams.deptId.length - 1] : undefined,
      };
      let queryResult = await queryList(params);
      tableData.value = queryResult.data.records;
      total.value = queryResult.data.total;
    } catch (e) {
      console.log(e);
    } finally {
      tableLoading.value = false;
    }
  }
  // 多选
  const multipleSelection = ref([]);
  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }
  // 批量删除
  function batchDelete() {
    console.log(multipleSelection.value);
  }
  // 删除数据
  async function handleDelete(row) {
    await useHandleData(deleteData, row.id, '确认删除');
    queryData();
  }
  const { goToDocDetail } = useGoToPage();
  async function handleViewItem(row) {
    if (!row?.id) {
      return;
    }
    goToDocDetail({
      id: row.id,
    });
  }

  let dialogOptions = reactive({
    title: '',
    visible: false,
    defaultValue: {},
    width: 600,
  });
  // 新增
  function handleAdd() {
    dialogOptions.title = '新增';
    dialogOptions.visible = true;
    dialogOptions.defaultValue = {};
  }

  function handleConfirm() {
    dialogOptions.visible = false;
    queryData();
  }

  function handleClose() {
    dialogOptions.visible = false;
    dialogOptions.defaultValue = {};
  }

  function handleUpdate(row) {
    dialogOptions.title = '修改';
    dialogOptions.visible = true;
    dialogOptions.defaultValue = row;
  }
  const formatType = (type) => {
    if (!type) {
      return '';
    }
    return routerTypeList.value.find((item) => item.value + '' === type + '')?.label;
  };
  const formatClassification = (classification) => {
    return cateList.value.find((item) => item.id + '' === classification + '')?.name;
  };
  const formatState = (state) => {
    return recordStates.value.find((item) => item.code + '' === state + '')?.text;
  };
  const routerTypeList = ref([]);
  const cateList = ref([]);
  const recordStates = ref([]);
  onMounted(async () => {
    let allStates = [{ code: 0, text: '全部' }].concat(allEnums['handbookRecordState']);
    recordStates.value = allStates.filter((item) => item.code !== 1);
    const { getSubMenu, subMenu } = useSubMenu();
    await getSubMenu();
    const bookCates = addRoutes.value?.find((item) => item.name === 'Book');
    let bookRouter = bookCates?.children;
    routerTypeList.value = bookRouter?.map((item) => {
      return {
        label: item?.meta?.title,
        value: item.id,
      };
    });
    for (let i = 0; i < bookRouter?.length; i++) {
      let res = await listMenu({ parentId: bookRouter[i].id });
      if (res.code === 200) {
        cateList.value = cateList.value.concat(
          res.data.map((item) => {
            return {
              id: item.id,
              name: item.name,
            };
          }),
        );
      }
    }

    await queryData();
  });
</script>

<style lang="scss" scoped></style>
